import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:dio/dio.dart';
import '../../services/ScreenAdatper.dart';
import '../../model/FocusModel.dart';
import '../../model/ProductModel.dart';
import '../../config/config.dart'; 

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  List _focusData = [];
  List _hotListData = [];
  List _bastListData = [];
  @override
  void initState() {
    super.initState();
    _getFocusData();
    _getHotData();
    _getBestData();
  }

  @override
  bool get wantKeepAlive => true;
  _getFocusData() async {
    var api = '${Config.domain}api/focus';
    var result = await Dio().get(api);
    var focus = FocusModel.fromJson(result.data);
    setState(() {
      this._focusData = focus.result;
    });
  }

  _getHotData() async {
    var api = '${Config.domain}api/plist?is_hot=1';
    var result = await Dio().get(api);
    var focus = ProductModel.fromJson(result.data);
    setState(() {
      this._hotListData = focus.result;
    });
  }

  _getBestData() async {
    var api = '${Config.domain}api/plist?is_bast=1';
    var result = await Dio().get(api);
    print(result.data is Map);
    var focus = ProductModel.fromJson(result.data);
    setState(() {
      this._bastListData = focus.result;
    });
  }

  Widget _swiperWidget() {
    if (this._focusData.length > 0) {
      return Container(
        child: AspectRatio(
          aspectRatio: 2 / 1,
          child: Swiper(
            itemBuilder: (BuildContext context, int index) {
              // url 的 \\ 斜杠是不会像js一样自动转回 / 的
              String pic = this._focusData[index].pic.replaceAll('\\', '/');
              return new Image.network(
                '${Config.domain}${pic}',
                fit: BoxFit.fill,
              );
            },
            itemCount: _focusData.length,
            pagination: new SwiperPagination(),
            autoplay: true,
          ),
        ),
      );
    } else {
      return Text('');
    }
  }

  Widget _titleWidget(value) {
    return Container(
      height: ScreenAdatper.height(32),
      margin: EdgeInsets.only(left: ScreenAdatper.width(20)),
      padding: EdgeInsets.only(left: ScreenAdatper.width(20)),
      decoration: BoxDecoration(
          border: Border(
              left: BorderSide(
                  color: Colors.red, width: ScreenAdatper.width(10.0)))),
      child: Text(
        value,
        style: TextStyle(color: Colors.black54),
      ),
    );
  }

  Widget _hotWidget() {
    if (this._hotListData.length > 0) {
      return Container(
        padding: EdgeInsets.all(ScreenAdatper.width(20)),
        height: ScreenAdatper.height(234),
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemBuilder: (context, index) {
            String sPic = this._hotListData[index].sPic;
            sPic = Config.domain + sPic.replaceAll('\\', '/');
            return Column(
              children: <Widget>[
                Container(
                  height: ScreenAdatper.height(140),
                  width: ScreenAdatper.width(140),
                  margin: EdgeInsets.only(right: ScreenAdatper.width(21)),
                  child: Image.network(
                    "${sPic}",
                    fit: BoxFit.cover,
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(top: ScreenAdatper.height(10)),
                  height: ScreenAdatper.height(44),
                  child: Text("￥${this._hotListData[index].price}",
                      style: TextStyle(color: Colors.red, fontSize: 16)),
                )
              ],
            );
          },
          itemCount: this._hotListData.length,
        ),
      );
    } else {
      return Text("");
    }
  }

  Widget _recProductWidget() {
    var itemWidth = (ScreenAdatper.getScreenWidth() - 30) / 2;
    return Container(
      padding: EdgeInsets.all(10),
      child: Wrap(
        runSpacing: 10,
        spacing: 10,
        children: this._bastListData.map((value) {
          String sPic = value.pic;
          sPic = Config.domain + sPic.replaceAll('\\', '/');
          return InkWell(
            onTap: () {
              Navigator.pushNamed(context, '/productContent',
                  arguments: {'id': value.sId});
            },
            child: Container(
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.black12, width: 1)),
              padding: EdgeInsets.all(10),
              width: itemWidth,
              child: Column(
                children: <Widget>[
                  Container(
                    width: double.infinity,
                    child: AspectRatio(
                      aspectRatio: 1 / 1,
                      child: Image.network(
                        "${sPic}",
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                  Container(
                    height: 48,
                    child: Padding(
                        padding: EdgeInsets.only(top: ScreenAdatper.height(20)),
                        child: Text(
                          value.title,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: Colors.black54),
                        )),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: ScreenAdatper.height(20)),
                    child: Stack(
                      children: <Widget>[
                        Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            '￥${value.price}',
                            style: TextStyle(color: Colors.red, fontSize: 16),
                          ),
                        ),
                        Align(
                          alignment: Alignment.centerRight,
                          child: Text(
                            '￥${value.oldPrice}',
                            style: TextStyle(
                                color: Colors.black54,
                                fontSize: 14,
                                decoration: TextDecoration.lineThrough),
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdatper.init(context);
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.center_focus_weak, size: 28, color: Colors.black87),
          onPressed: () {},
        ),
        title: InkWell(
          child: Container(
            padding: EdgeInsets.only(left: ScreenAdatper.width(30)),
            height: ScreenAdatper.height(68),
            decoration: BoxDecoration(
                color: Color.fromRGBO(233, 233, 233, 0.8),
                borderRadius: BorderRadius.circular(30)),
            child: Row(
              children: <Widget>[
                Icon(Icons.search),
                Text(
                  "笔记本",
                  style: TextStyle(fontSize: ScreenAdatper.size(28)),
                )
              ],
            ),
          ),
          onTap: () {
            Navigator.pushNamed(context, '/search');
          },
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.message, size: 28, color: Colors.black87),
            onPressed: () {},
          )
        ],
      ),
      body: ListView(
        children: <Widget>[
          _swiperWidget(),
          SizedBox(
            height: ScreenAdatper.height(20),
          ),
          _titleWidget("猜你喜欢"),
          _hotWidget(),
          SizedBox(
            height: ScreenAdatper.height(20),
          ),
          _titleWidget("热门推荐"),
          _recProductWidget()
        ],
      ),
    );
  }
}
